import { user } from "@/api"
import { useUserStore } from "@/store/user"
import { App } from "vue"
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"
import LoginVue from "../Login/Login.vue"

const routes: RouteRecordRaw[] = [{
    path: "/login",
    name: "login",
    component: LoginVue
},
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    console.log(from.path);
    const token = localStorage.getItem("token")
    if (!token && to.path !== "/login") {
        next("/login")
    }
    // 有token就哪里来到哪里去
    if (token && to.path == "/login") {
        next(from.path)
    }

    const userStore = useUserStore()
    console.log("from", from);


    if (token && userStore.menus.length === 0 && router.getRoutes().length === 1 && (from.path == "/" || from.path == "/login")) {
        user.LoginUserApi().then(res => {
            userStore.menus = res.data.menus
            userStore.username = res.data.username
            console.log("有数据");
            // 有数据了然后去动态生成路由
            // router.addRoute(route)
            userStore.activeMenus.forEach((item) => {
                const route: RouteRecordRaw = {
                    path: "/" + item.name,
                    name: item.name,
                    component: () => import("../Home/Home.vue"),
                    children: []
                }
                item.children?.forEach(child => {
                    route.children?.push({
                        path: `/${item.name}/${child.name}`,
                        name: child.name,
                        component: () => import(`@/views/${item.name}/${child.name}.vue`)
                    })
                })
                router.addRoute(route)

            })
            router.addRoute({
                path: "/",
                name: "home",
                redirect: "/index",
                component: () => import("../Home/Home.vue"),
                children: [{
                    path: "/index",
                    name: "index",
                    component: () => import("../views/index/index.vue")
                }
                ]
            })
            // 刷新 登录 
            next(to.path);
        })

    } else {
        // 登陆页面

        next()
    }

})

export default (app: App<Element>) => {
    app.use(router)
}

export { router }
